import Vue from 'vue'
import VueRouter from "vue-router";
import store from '@/store'
Vue.use(VueRouter)

import routes from "@/router/routes";
//为了解决promise的问题
const originPush=VueRouter.prototype.push
VueRouter.prototype.push=function (location,resolved,rejected){
    if (resolved===undefined&&rejected===undefined){
        return originPush.call(this,location).catch(()=>{})
    }else {
        return originPush.call(this,location,resolved,rejected)
    }
}
const originReplace=VueRouter.prototype.replace
VueRouter.prototype.replace=function (location,resolved,rejected){
    if (resolved===undefined&&rejected===undefined){
        return originReplace.call(this,location).catch(()=>{})
    }else {
        return originReplace.call(this,location,resolved,rejected)
    }
}
const router=new VueRouter({
    routes,
    scrollBehavior (to, from, savedPosition) {
        return { x: 0, y: 0 }
    }
})
//token校验 获取用户的信息后展示页面
router.beforeEach(async (to, from, next) => {
   //获取token 获取用户信息 先写store
    let token=store.state.user.token
    let userInfo=store.state.user.userInfo
    //判断token存在不

    if (token){
        //如果存在 表明用户以已经登录
        if (to.path==='/login'){
            //如果是在登录页面也要跳转到登录页面 强制跳转到'/home'页面
            next('/')
        }else {
            //有token了 在判断一下用户信息是否存在
            if (userInfo.name){
                //如果存在 无条件放行
                next()
            }else {
                try {
                    //如果用户信息不存在 需要重新发请求 然后跳转到登录页面
                    await store.dispatch('getUserInfo')
                    next()
                }catch (error){
                    //如果报错 说明token已经过期.需要清空token 重新登录
                    await store.dispatch('resetToken')//清空token
                    next('/login')
                }
            }
        }
    }else {
        //如果token不存在 这个逻辑以后在添加 先无条件放行
     /*   next()*/
        let targetPath=to.path
        if (targetPath.indexOf('/trade')===0||targetPath.startsWith('/pay')||targetPath.startsWith('/center')){
            next('/login?redirect='+targetPath)
        }else {
            next()
        }
    }
})
export default router